package com.duan.laugh.common.security.config;

import com.duan.laugh.common.security.component.LaughUserAuthenticationConverter;
import com.duan.laugh.common.security.exception.LaughAccessDeniedHandler;
import com.duan.laugh.common.security.exception.LaughAuthExceptionEntryPoint;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.DefaultAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.RemoteTokenServices;
import org.springframework.security.oauth2.provider.token.UserAuthenticationConverter;
import org.springframework.web.client.RestTemplate;

/**
 * 使用restTemplate负载均衡
 * token获取用户信息转成用户的详细信息
 * 动态设置不拦截的url：security.oauth2.client.ignore-url-list
 *
 * @author duanjw
 */
@Configuration
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
    @Autowired
    protected RemoteTokenServices remoteTokenServices;
    @Autowired
    private RestTemplate lbRestTemplate;
    @Autowired
    private IgnoreUrlProperties ignoreUrlProperties;

    @Override
    @SneakyThrows
    public void configure(HttpSecurity httpSecurity) {
        //允许使用iframe 嵌套，避免swagger-ui 不被加载的问题
        httpSecurity.headers().frameOptions().disable();
        ExpressionUrlAuthorizationConfigurer<HttpSecurity>
                .ExpressionInterceptUrlRegistry registry = httpSecurity
                .authorizeRequests();
        ignoreUrlProperties.getIgnoreUrlList().forEach(url -> registry.antMatchers(url).permitAll());
        registry.anyRequest().authenticated()
                .and().csrf().disable();
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        DefaultAccessTokenConverter accessTokenConverter = new DefaultAccessTokenConverter();
        UserAuthenticationConverter userTokenConverter = new LaughUserAuthenticationConverter();
        accessTokenConverter.setUserTokenConverter(userTokenConverter);

        remoteTokenServices.setRestTemplate(lbRestTemplate);
        remoteTokenServices.setAccessTokenConverter(accessTokenConverter);
        resources.tokenServices(remoteTokenServices);

        resources.authenticationEntryPoint(new LaughAuthExceptionEntryPoint()).accessDeniedHandler(new LaughAccessDeniedHandler());
    }
}
